package com.jdone.compus.controller;

import com.jdone.compus.dto.ApiResponse;
import com.jdone.compus.dto.JwtAuthenticationResponse;
import com.jdone.compus.service.VerifyUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;

@RestController
@RequestMapping("/blow/api/saas")
@Api(tags = "青橄榄 SaaS 用户校验")
@RequiredArgsConstructor
public class VerifyUserController {

    @Autowired
    private VerifyUserService service;

    @ApiOperation("8/10校验用户信息并返回本地 JWT（若第三方校验通过）")
    @PostMapping("/verify-user")
    public ApiResponse verifyUser(
            @RequestParam
            @ApiParam("从跳转链接中获取的 Authorization 完整字符串") String token) {

        try {
            // service 方法会抛出异常或返回 jwt 字符串
            String jwt = service.verifyUserAndIssueJwt(token);
            // 跟你的登录方法返回格式一致
            return new ApiResponse(true, "登录成功", new JwtAuthenticationResponse(jwt));
        } catch (ResponseStatusException ex) {
            // 已知的校验错误（例如第三方返回 401）
            return new ApiResponse(false, ex.getReason(), null);
        } catch (IllegalArgumentException ex) {
            return new ApiResponse(false, ex.getMessage(), null);
        } catch (Exception ex) {
            return new ApiResponse(false, "服务内部错误", null);
        }
    }

}
